<template>

    <div>
        <p>
            <button @click="list" class="btn btn-white btn-default btn-round">
                <i class="ace-icon fa fa-refresh green"></i>
                刷新
            </button>
            &nbsp;
            <button @click="add" class="btn btn-white btn-default btn-round">
                <i class="ace-icon fa fa-edit red"></i>
                新增
            </button>
        </p>
        <pagination ref="pagination" v-bind:list="list"></pagination>
        <table id="simple-table" class="table  table-bordered table-hover">
            <thead>
            <tr>
                        <th>id</th>

                        <th>角色</th>

                        <th>描述</th>
                <th>操作</th>
            </tr>
            </thead>

            <tbody>
            <tr v-for="role in roles">
                            <td>{{role.id}}</td>
                            <td>{{role.name}}</td>
                            <td>{{role.desc}}</td>

                <td>
                    <div class="hidden-sm hidden-xs btn-group">
                        <button @click="editUser(role)" class="btn btn-white btn-sm btn-info">
                            <i class="ace-icon fa fa-user bigger-120"></i>关联用户
                        </button>
                        <button @click="editResource(role)" class="btn btn-white btn-sm btn-success">
                            <i class="ace-icon fa fa-list bigger-120"></i>权限
                        </button>

                        <button @click="edit(role)" class="btn btn-white btn-sm btn-info">
                            <i class="ace-icon fa fa-pencil bigger-120"></i>编辑
                        </button>

                        <button @click="handledelete(role.id)" class="btn btn-white btn-sm btn-danger">
                            <i class="ace-icon fa fa-trash-o bigger-120"></i>删除
                        </button>

                    </div>

                    <div class="hidden-md hidden-lg">
                        <div class="inline pos-rel">
                            <button class="btn btn-minier btn-primary dropdown-toggle" data-toggle="dropdown"
                                    data-position="auto">
                                <i class="ace-icon fa fa-cog icon-only bigger-110"></i>
                            </button>

                            <ul class="dropdown-menu dropdown-only-icon dropdown-yellow dropdown-menu-right dropdown-caret dropdown-close">
                                <li>
                                    <a @click="editUser(role)" class="tooltip-error" data-rel="tooltip" title="关联用户">
																			<span class="blue">
																				<i class="ace-icon fa fa-search-plus bigger-120"></i>
																			</span>
                                    </a>
                                </li>
                                <li>
                                    <a @click="editResource(role)" class="tooltip-info" data-rel="tooltip" title="权限">
																			<span class="blue">
																				<i class="ace-icon fa fa-search-plus bigger-120"></i>
																			</span>
                                    </a>
                                </li>

                                <li>
                                    <a @click="edit(role)" class="tooltip-success" data-rel="tooltip" title="编辑">
																			<span class="green">
																				<i class="ace-icon fa fa-pencil-square-o bigger-120"></i>
																			</span>
                                    </a>
                                </li>

                                <li>
                                    <a @click="handledelete(role.id)" class="tooltip-error" data-rel="tooltip" title="删除">
																			<span class="red">
																				<i class="ace-icon fa fa-trash-o bigger-120"></i>
																			</span>
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </td>
            </tr>
            </tbody>
        </table>
        <!-- /.span -->

        <div class="modal fade" id="myModal" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">表单</h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal">

                                            <div class="form-group">
                                                <label class="col-sm-2 control-label">角色:</label>
                                                <div class="col-sm-10">
                                                    <input type="text" v-model="roleinfo.name" class="form-control" placeholder="角色">
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label class="col-sm-2 control-label">描述:</label>
                                                <div class="col-sm-10">
                                                    <input type="text" v-model="roleinfo.desc" class="form-control" placeholder="描述">
                                                </div>
                                            </div>

                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button type="button" @click="save" class="btn btn-primary">保存</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
        <!-- 角色资源关联配置 -->
        <div id="resource-modal" class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">角色资源关联配置</h4>
                    </div>
                    <div class="modal-body">
                        <ul id="tree" class="ztree"></ul>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-white btn-default btn-round" data-dismiss="modal">
                            <i class="ace-icon fa fa-times"></i>
                            关闭
                        </button>
                        <button type="button" class="btn btn-white btn-info btn-round" v-on:click="saveResource()">
                            <i class="ace-icon fa fa-plus blue"></i>
                            保存
                        </button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
        <!-- 角色用户关联配置 -->
        <div id="user-modal" class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">角色用户关联配置</h4>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <table id="user-table" class="table table-hover">
                                    <tbody>
                                    <tr v-for="user in users">
                                        <td>{{user.loginName}}</td>
                                        <td class="text-right">
                                            <a v-on:click="addUser(user)" href="javascript:;" class="">
                                                <i class="ace-icon fa fa-arrow-circle-right blue"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    </tbody>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <table id="role-user-table" class="table table-hover">
                                    <tbody>
                                    <tr v-for="user in roleUsers">
                                        <td>{{user.loginName}}</td>
                                        <td class="text-right">
                                            <a v-on:click="deleteUser(user)" href="javascript:;" class="">
                                                <i class="ace-icon fa fa-trash blue"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-white btn-default btn-round" data-dismiss="modal">
                            <i class="ace-icon fa fa-times"></i>
                            关闭
                        </button>
                        <button type="button" class="btn btn-white btn-info btn-round" v-on:click="saveUser()">
                            <i class="ace-icon fa fa-plus blue"></i>
                            保存
                        </button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
    </div><!-- /.row -->


</template>


<script scope>
    import axios from 'axios';
    import {defineComponent, onMounted, ref} from 'vue';
    import Pagination from '@/components/pagination.vue';

    export default defineComponent({
        name: 'role',
        components:{
            Pagination
        },
        setup() {
            const roles = ref();
            const pagination = ref({});
            const roleinfo=ref({});
            let tree={};
            const resources=ref({});
            const roleId=ref();
            const users=ref();
            const roleUsers=ref([]);
            const list = () => {
                Loading.show();
                axios.get("/system/admin/role/list", {
                    params: {
                        page: pagination.value.page,
                        size: pagination.value.size,
                    }
                }).then((response) => {
                    Loading.hide();
                    const data=response.data;
                    if (data.success){
                        roles.value = data.content.list;
                        pagination.value.render(pagination.value.page,data.content.total);
                    }else {
                        Loading.hide();
                        Toast.warning(data.message);
                    }

                })
            };

            const add=()=>{
                roleinfo.value={};
                $('#myModal').modal();
            };

            /**
             * 编辑
             */
            const edit = (role) => {
                $('#myModal').modal();
                roleinfo.value = Tool.copy(role);
            };

            /**
             * 删除
             */
            const handledelete = (id) => {
                Confirm.show("删除角色后不可恢复，确认删除？", function () {
                    Loading.show();
                    axios.delete("/system/admin/role/delete/" + id).then((response) => {
                        Loading.hide();
                        const data = response.data;
                        if (data.success) {
                            list();
                            Toast.success("删除成功!");
                        }else{
                            Loading.hide();
                            Toast.warning(data.message);
                        }
                    })
                });
            };

            const save=()=>{
                // 保存校验
                if (1 != 1
                    || !Validator.require(roleinfo.value.name, "角色")
                    || !Validator.length(roleinfo.value.name, "角色", 1, 50)
                    || !Validator.require(roleinfo.value.desc, "描述")
                    || !Validator.length(roleinfo.value.desc, "描述", 1, 100)
                ) {
                    return;
                }

                Loading.show();
                axios.post("/system/admin/role/save",roleinfo.value).then((response) => {
                    const data=response.data;
                    if (data.success){
                        Loading.hide();
                        $('#myModal').modal('hide');
                        // console.log(data);
                        list();
                        Toast.success("保存成功！");
                    }else{
                        Loading.hide();
                        Toast.warning(data.message);
                    }

                })
            };

            /**
             * 加载资源树
             */
          const loadResource=()=>{
                Loading.show();
                axios.get('/system/admin/resource/load-tree').then((res)=>{
                    Loading.hide();
                    let response = res.data;
                    resources.value = response.content;
                    // 初始化树
                    initTree();
                    listRoleResource();
                })
            }

            /**
             * 点击【编辑】
             */
            const editResource=(role)=>{
                loadResource();
                roleId.value=role.id;
                $("#resource-modal").modal("show");
            }

            /**
             * 初始资源树
             */
           const initTree=()=> {
                let setting = {
                    check: {
                        enable: true
                    },
                    data: {
                        simpleData: {
                            idKey: "id",
                            pIdKey: "parent",
                            rootPId: "",
                            enable: true
                        }
                    }
                };

                tree = $.fn.zTree.init($("#tree"), setting, resources.value);
                tree.expandAll(true);
            }

            /**
             * 资源模态框点击【保存】
             */
            const saveResource=()=>{
                let resources = tree.getCheckedNodes();
                console.log("勾选的资源：", resources);

                // 保存时，只需要保存资源id，所以使用id数组进行参数传递
                let resourceIds = [];
                for (let i = 0; i < resources.length; i++) {
                    resourceIds.push(resources[i].id);
                }

                axios.post( '/system/admin/role/save-resource', {
                    id: roleId.value,
                    resourceIds: resourceIds
                }).then((response)=>{
                    let resp = response.data;
                    if (resp.success) {
                        Toast.success("保存成功!");
                        $("#resource-modal").modal("hide");
                    } else {
                        Toast.warning(resp.message);
                    }
                });
            }

            /**
             * 加载角色资源关联记录
             */
           const listRoleResource=()=>{
                axios.get('/system/admin/role/list-resource/' + roleId.value).then((response)=>{
                    let resp = response.data;
                    let resources = resp.content;

                    // 勾选查询到的资源：先把树的所有节点清空勾选，再勾选查询到的节点
                    tree.checkAllNodes(false);
                    for (let i = 0; i < resources.length; i++) {
                        let node = tree.getNodeByParam("id", resources[i]);
                        tree.checkNode(node, true);
                    }
                });
            }

            /**
             * 点击【用户】
             */
           const editUser=(role)=>{
                roleId.value=role.id;
                listUser();
                listRoleUser();
                $("#user-modal").modal("show");
            }

            /**
             * 查询所有用户
             */
            const listUser=()=>{
                let _this = this;
                axios.get('/system/admin/user/list', {
                    page: 1,
                    size: 9999
                }).then((response)=>{
                    let resp = response.data;
                    if (resp.success) {
                        users.value = resp.content.list;
                    } else {
                        Toast.warning(resp.message);
                    }
                })
            }

            /**
             * 角色中增加用户
             */
            const addUser=(user)=>{
                let _this = this;

                // 如果当前要添加的用户在右边列表中已经有了，则不用再添加
                let users = roleUsers.value;
                for (let i = 0; i < users.length; i++) {
                    if (user === users[i]) {
                        return;
                    }
                }

                roleUsers.value.push(user);
            }

            /**
             * 角色中删除用户
             */
           const deleteUser=(user)=>{
                Tool.removeObj(roleUsers.value, user);
            }

            /**
             * 角色用户模态框点击【保存】
             */
           const saveUser=()=>{
                let users = roleUsers.value;

                // 保存时，只需要保存用户id，所以使用id数组进行参数传递
                let userIds = [];
                for (let i = 0; i < users.length; i++) {
                    userIds.push(users[i].id);
                }
                axios.post( '/system/admin/role/save-user', {
                    id: roleId.value,
                    userIds: userIds
                }).then((response)=>{
                    console.log("保存角色用户结果：", response);
                    let resp = response.data;
                    if (resp.success) {
                        Toast.success("保存成功!");
                        $("#user-modal").modal("hide");
                    } else {
                        Toast.warning(resp.message);
                    }
                })
            }

            /**
             * 加载角色用户
             */
            const listRoleUser=()=>{
                roleUsers.value = [];
                axios.get( '/system/admin/role/list-user/' + roleId.value).then((res)=>{
                    let response = res.data;
                    let userIds = response.content;

                    // 根据加载到用户ID，到【所有用户数组：users】中查找用户对象，用于列表显示
                    for (let i = 0; i < userIds.length; i++) {
                        for (let j = 0; j < users.value.length; j++) {
                            if (userIds[i] === users.value[j].id) {
                                roleUsers.value.push(users.value[j]);
                            }
                        }
                    }
                });
            }

            onMounted(() => {
                list();
            });

            return {
                list,
                add,
                edit,
                handledelete,
                pagination,
                roleinfo,
                save,
                roles,
                editResource,
                saveResource,
                editUser,
                users,
                roleUsers,
                addUser,
                deleteUser,
                saveUser
            }


        }
    });
</script>